<template>
  <!-- 保持原有模板内容不变 -->
  <div class="max-w-2xl mx-auto space-y-6">
    <!-- 进度条 -->
    <Card>
      <CardContent class="pt-6">
        <div class="flex justify-between items-center mb-2">
          <span class="text-sm">{{ t('reactionTimeTest.progress') }}</span>
          <span class="text-sm">{{ currentRound }}/{{ totalRounds }}</span>
        </div>
        <Progress :modelValue="(currentRound / totalRounds) * 100" />
      </CardContent>
    </Card>

    <!-- 主测试区域 -->
    <Card class="aspect-square">
      <CardContent
        class="h-full flex flex-col items-center justify-center p-8 cursor-pointer"
        @click="handleReaction"
      >
        <!-- 准备状态 -->
        <div v-if="state === 'ready'" class="text-center space-y-6">
          <Zap class="w-16 h-16 text-yellow-500 mx-auto" />
          <div>
            <h2 class="text-2xl font-bold mb-2">{{ t('reactionTimeTest.areYouReady') }}</h2>
            <p class="text-muted-foreground mb-4">
              {{ t('reactionTimeTest.waitForGreen') }}
            </p>
            <Badge variant="secondary">
              {{ t('reactionTimeTest.round', { currentRound: currentRound + 1, totalRounds: totalRounds }) }}
            </Badge>
          </div>
          <Button
            size="lg"
            @click.stop="startRound"
            class="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
          >
            <Zap class="w-5 h-5 mr-2" />
            {{ t('reactionTimeTest.startTest') }}
          </Button>
        </div>

        <!-- 等待状态 -->
        <div
          v-else-if="state === 'waiting'"
          class="text-center space-y-6 pointer-events-none"
        >
          <div
            class="w-24 h-24 bg-red-500 rounded-full flex items-center justify-center mx-auto"
          >
            <span class="text-4xl font-bold text-white">
              {{ countdown > 0 ? countdown : "..." }}
            </span>
          </div>
          <div>
            <h2 class="text-2xl font-bold text-red-500 mb-2">{{ t('reactionTimeTest.waiting') }}</h2>
            <p class="text-muted-foreground">{{ t('reactionTimeTest.dontClick') }}</p>
          </div>
        </div>

        <!-- 反应状态 -->
        <div
          v-else-if="state === 'react'"
          class="text-center space-y-6 w-full h-full flex flex-col items-center justify-center bg-green-500 rounded-lg pointer-events-none"
        >
          <div class="text-6xl font-bold text-white">!</div>
          <div>
            <h2 class="text-3xl font-bold text-white mb-2">{{ t('reactionTimeTest.clickNow') }}</h2>
            <p class="text-green-100">{{ t('reactionTimeTest.clickOrSpace') }}</p>
          </div>
        </div>

        <!-- 过早点击状态 -->
        <div v-else-if="state === 'too-early'" class="text-center space-y-6">
          <div
            class="w-24 h-24 bg-red-500 rounded-full flex items-center justify-center mx-auto"
          >
            <span class="text-4xl font-bold text-white">✕</span>
          </div>
          <div>
            <h2 class="text-2xl font-bold text-red-500 mb-2">{{ t('reactionTimeTest.tooEarly') }}</h2>
            <p class="text-muted-foreground mb-4">{{ t('reactionTimeTest.clickedTooEarly') }}</p>
          </div>
          <Button
            @click.stop="setState('ready')"
            class="bg-gradient-to-r from-orange-500 to-red-500 text-white hover:from-orange-600 hover:to-red-600 shadow-md hover:shadow-lg transition-all duration-200"
          >
            {{ t('reactionTimeTest.retryRound') }}
          </Button>
        </div>
        <!-- 测试完成界面 -->
        <div v-else-if="state === 'complete'" class="max-w-2xl mx-auto space-y-6">
          <Card>
            <CardHeader class="text-center">
              <CardTitle class="flex items-center justify-center gap-2">
                <Target class="w-6 h-6 text-green-500" />
                {{ t('reactionTimeTest.testComplete') }}
              </CardTitle>
            </CardHeader>
            <CardContent class="space-y-6">
              <div class="text-center space-y-4">
                <div class="text-6xl font-bold text-primary">
                  {{ getAverageTime() }}ms
                </div>
                <div :class="`text-xl font-semibold ${getRating().color}`">
                  {{ getRating().text }}
                </div>
                <div class="text-lg">
                  {{ t('reactionTimeTest.finalScore') }}
                  <span class="font-bold text-primary">{{ getScore() }}</span>
                </div>
              </div>

              <div class="grid grid-cols-3 gap-4">
                <div class="text-center p-4 bg-muted rounded-lg">
                  <div class="text-2xl font-bold">
                    {{
                      reactionTimes.length > 0 ? Math.min(...reactionTimes) : 0
                    }}ms
                  </div>
                  <div class="text-sm text-muted-foreground">{{ t('reactionTimeTest.fastestReaction') }}</div>
                </div>
                <div class="text-center p-4 bg-muted rounded-lg">
                  <div class="text-2xl font-bold">
                    {{
                      reactionTimes.length > 0 ? Math.max(...reactionTimes) : 0
                    }}ms
                  </div>
                  <div class="text-sm text-muted-foreground">{{ t('reactionTimeTest.slowestReaction') }}</div>
                </div>
                <div class="text-center p-4 bg-muted rounded-lg">
                  <div class="text-2xl font-bold">
                    {{ calculateConsistency() }}%
                  </div>
                  <div class="text-sm text-muted-foreground">{{ t('reactionTimeTest.consistency') }}</div>
                </div>
              </div>

              <div class="space-y-2">
                <h3 class="font-semibold">{{ t('reactionTimeTest.roundScores') }}</h3>
                <div class="grid grid-cols-5 gap-2">
                  <div
                    v-for="(time, index) in reactionTimes"
                    :key="index"
                    class="text-center p-2 bg-muted rounded"
                  >
                    <div class="font-semibold">{{ time }}ms</div>
                    <div class="text-xs text-muted-foreground">
                      {{ t('reactionTimeTest.roundLabel', { round: index + 1 }) }}
                    </div>
                  </div>
                </div>
              </div>

              <div class="flex gap-4">
                <Button
                  @click="resetTest"
                  variant="outline"
                  class="flex-1 border-2 border-slate-300 hover:border-blue-500 hover:bg-blue-50 hover:text-blue-700 transition-all duration-200"
                >
                  <RotateCcw class="w-4 h-4 mr-2" />
                  {{ t('reactionTimeTest.retest') }}
                </Button>
                <Button
                  @click="handleComplete"
                  class="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:from-green-600 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-200"
                >
                  {{ t('reactionTimeTest.saveResult') }}
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </CardContent>
    </Card>

    <!-- 当前成绩 -->
    <Card v-if="reactionTimes.length > 0 && state !== 'complete'">
      <CardHeader>
        <CardTitle class="flex items-center gap-2">
          <Timer class="w-5 h-5" />
          {{ t('reactionTimeTest.currentScore') }}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div class="grid grid-cols-3 gap-4 text-center">
          <div>
            <div class="text-2xl font-bold">{{ getAverageTime() }}ms</div>
            <div class="text-sm text-muted-foreground">{{ t('reactionTimeTest.averageTime') }}</div>
          </div>
          <div>
            <div class="text-2xl font-bold">
              {{ reactionTimes.length > 0 ? Math.min(...reactionTimes) : 0 }}ms
            </div>
            <div class="text-sm text-muted-foreground">{{ t('reactionTimeTest.fastest') }}</div>
          </div>
          <div>
            <div class="text-2xl font-bold">{{ reactionTimes.length }}</div>
            <div class="text-sm text-muted-foreground">{{ t('reactionTimeTest.completed') }}</div>
          </div>
        </div>
      </CardContent>
    </Card>

    <!-- 测试说明 -->
    <Card>
      <CardContent class="pt-6">
        <h3 class="font-semibold mb-2">{{ t('reactionTimeTest.instructions') }}</h3>
        <ul class="text-sm text-muted-foreground space-y-1">
          <li>{{ t('reactionTimeTest.instruction1') }}</li>
          <li>{{ t('reactionTimeTest.instruction2') }}</li>
          <li>{{ t('reactionTimeTest.instruction3', { totalRounds: totalRounds }) }}</li>
          <li>{{ t('reactionTimeTest.instruction4') }}</li>
        </ul>
      </CardContent>
    </Card>

  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { Zap, Timer, Target, RotateCcw } from "lucide-vue-next";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const props = defineProps({
  onComplete: {
    type: Function,
    required: true,
  },
});

const state = ref("ready");
const currentRound = ref(0);
const reactionTimes = ref([]);
const startTime = ref(0);
const testStartTime = ref(0);
const countdown = ref(0);
const timeoutId = ref(null);

const totalRounds = 5;
const maxWaitTime = 5000;
const minWaitTime = 1000;

const setCountdown = (callback) => {
  countdown.value = callback(countdown.value);
};

const startRound = () => {
  if (currentRound.value === 0 && reactionTimes.value.length === 0) {
    testStartTime.value = Date.now();
  }

  state.value = "waiting";
  countdown.value = 3;

  const countdownInterval = setInterval(() => {
    setCountdown((prev) => {
      if (prev <= 1) {
        clearInterval(countdownInterval);
        const delay = minWaitTime + Math.random() * (maxWaitTime - minWaitTime);
        const timeout = setTimeout(() => {
          startTime.value = Date.now();
          state.value = "react";
        }, delay);

        timeoutId.value = timeout;
        return 0;
      }
      return prev - 1;
    });
  }, 1000);
};

const handleReaction = () => {
  if (state.value === "waiting") {
    state.value = "too-early";
    if (timeoutId.value) {
      clearTimeout(timeoutId.value);
      timeoutId.value = null;
    }
    return;
  }

  if (state.value === "react") {
    const reactionTime = Date.now() - startTime.value;
    reactionTimes.value = [...reactionTimes.value, reactionTime];

    if (currentRound.value + 1 >= totalRounds) {
      state.value = "complete";
    } else {
      currentRound.value++;
      state.value = "ready";
    }
  }
};

const resetTest = () => {
  state.value = "ready";
  currentRound.value = 0;
  reactionTimes.value = [];
  startTime.value = 0;
  testStartTime.value = 0;
  countdown.value = 0;
  if (timeoutId.value) {
    clearTimeout(timeoutId.value);
    timeoutId.value = null;
  }
};

const getAverageTime = () => {
  if (reactionTimes.value.length === 0) return 0;
  return Math.round(
    reactionTimes.value.reduce((a, b) => a + b, 0) / reactionTimes.value.length
  );
};

const getScore = () => {
  const avgTime = getAverageTime();
  if (avgTime < 200) return 100;
  if (avgTime < 250) return 90;
  if (avgTime < 300) return 80;
  if (avgTime < 350) return 70;
  if (avgTime < 400) return 60;
  if (avgTime < 500) return 50;
  return 40;
};

const setState = (value) => {
  state.value = value;
};

const getRating = () => {
  const avgTime = getAverageTime();
  if (avgTime < 200) return { text: t('reactionTimeTest.rating_lightning'), color: "text-yellow-500" };
  if (avgTime < 250) return { text: t('reactionTimeTest.rating_very_fast'), color: "text-green-500" };
  if (avgTime < 300) return { text: t('reactionTimeTest.rating_fast'), color: "text-blue-500" };
  if (avgTime < 350) return { text: t('reactionTimeTest.rating_normal'), color: "text-gray-500" };
  if (avgTime < 400) return { text: t('reactionTimeTest.rating_slow'), color: "text-orange-500" };
  return { text: t('reactionTimeTest.rating_needs_improvement'), color: "text-red-500" };
};

const calculateConsistency = () => {
  if (reactionTimes.value.length === 0) return 0;
  const avg = getAverageTime();
  if (avg === 0) return 0;
  const variance =
    reactionTimes.value.reduce(
      (sum, time) => sum + Math.pow(time - avg, 2),
      0
    ) / reactionTimes.value.length;
  const standardDeviation = Math.sqrt(variance);
  const consistency = 100 - (standardDeviation / avg) * 100;
  return Math.max(0, Math.min(100, Math.round(consistency)));
};

const handleComplete = () => {
  const avgTime = getAverageTime();
  const score = getScore();
  const testDuration = Math.round((Date.now() - testStartTime.value) / 1000);

  const result = {
    id: Date.now().toString(),
    testType: "reaction",
    score: score,
    completedAt: new Date(),
    duration: testDuration,
    details: {
      averageReactionTime: avgTime,
      reactionTimes: [...reactionTimes.value],
      totalRounds: reactionTimes.value.length,
      bestTime:
        reactionTimes.value.length > 0 ? Math.min(...reactionTimes.value) : 0,
      worstTime:
        reactionTimes.value.length > 0 ? Math.max(...reactionTimes.value) : 0,
      consistency: calculateConsistency(),
      rating: getRating().text,
      averageTime: avgTime,
    },
  };
  props.onComplete(result);
};

const handleKeyPress = (e) => {
  if (
    e.code === "Space" &&
    (state.value === "waiting" || state.value === "react")
  ) {
    e.preventDefault();
    handleReaction();
  }
};

onMounted(() => {
  document.addEventListener("keydown", handleKeyPress);
});

onUnmounted(() => {
  document.removeEventListener("keydown", handleKeyPress);
  if (timeoutId.value) {
    clearTimeout(timeoutId.value);
  }
});
</script>